package com.mofang.ticketing.common.mq.rabbit.component;

import com.mofang.ticketing.common.mq.rabbit.util.RabbitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListenerConfigurer;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistrar;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;
import org.springframework.messaging.handler.annotation.support.MessageHandlerMethodFactory;

/**
 * @author LGC
 */
@Slf4j
@AutoConfiguration
public class RabbitAutoConfig implements RabbitListenerConfigurer {

    @Bean
    public RabbitUtil rabbitUtil(RabbitTemplate rabbitTemplate) {
        return new RabbitUtil(rabbitTemplate);
    }

    @Override
    public void configureRabbitListeners(RabbitListenerEndpointRegistrar rabbitListenerEndpointRegistrar) {
        rabbitListenerEndpointRegistrar.setMessageHandlerMethodFactory(messageHandlerMethodFactory());
    }

    @Bean
    public MessageHandlerMethodFactory messageHandlerMethodFactory() {
        DefaultMessageHandlerMethodFactory messageHandlerMethodFactory = new DefaultMessageHandlerMethodFactory();
        messageHandlerMethodFactory.setMessageConverter(mappingJackson2MessageConverter());
        return messageHandlerMethodFactory;
    }

    @Bean
    public MappingJackson2MessageConverter mappingJackson2MessageConverter() {
        return new MappingJackson2MessageConverter();
    }


    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback((correlationData, b, s) -> {
            log.info("ConfirmCallback:相关数据：{}", correlationData);
            log.info("ConfirmCallback:确认情况：{}", b);
            log.info("ConfirmCallback:原因：{}", s);

        });
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            log.info("消息：{}", returnedMessage.getMessage());
            log.info("回应码：{}", returnedMessage.getReplyCode());
            log.info("回应信息：{}", returnedMessage.getReplyText());
            log.info("交换机：{}", returnedMessage.getExchange());
            log.info("路由键：{}", returnedMessage.getRoutingKey());
        });
        return rabbitTemplate;
    }
}
